package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
@Slf4j
public class AccountTccActionImpl implements AccountTccAction {
    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long userId, BigDecimal money) {
        log.info("减少账户金额，第一阶段锁定金额，userId=" + userId + "， money=" + money);

        Account account = accountMapper.selectById(userId);
        if (account.getResidue().compareTo(money) < 0) {  //判断可用金额是否有那么多
            throw new RuntimeException("账户金额不足");
        }

        /*
        余额-money
        冻结+money
         */
        accountMapper.updateResidueToFrozen(userId, money);

        //保存标识
        ResultHolder.setResult(getClass(), ctx.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext ctx) {  //加synchronized锁  保证在提交时遇到阻塞时,第二次发送提交请求时,保证两次提交请求不重复删除标记
        // Long userId = Long.valueOf(ctx.getActionContext("userId").toString()); 也还可用转成Long对象
        long userId = Long.parseLong(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        log.info("减少账户金额，第二阶段，提交，userId=" + userId + "， money=" + money);

        //防止重复提交
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            return true;
        }
        accountMapper.updateFrozenToUsed(userId, money);

        //删除标识
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext ctx) {
        // Long userId = Long.valueOf(ctx.getActionContext("userId").toString()); 也还可用转成Long对象
        long userId = Long.parseLong(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        log.info("减少账户金额，第二阶段，回滚，userId=" + userId + "， money=" + money);

        //防止重复回滚
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            return true;
        }

        accountMapper.updateFrozenToResidue(userId, money);

        //删除标识
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;

    }
}
